# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/15'
__author__ = 'Just'
__filename__ = 'clientservice'
"""
import json
from flask import current_app
from app.libs.error_code import AuthFailedException
import requests


class ClientService:
    """客户端登录注册service"""
    wx_data = None      # 微信登录数据
    client_type = 0     # 客户端类型

    def __init__(self, form):
        if form:
            self.form = form
            self.client_type = form.type.object_data

    def register_by_email(self):
        """拦截 进行邮箱验证再注册"""
        # flash('一封激活邮件已发送至您的邮箱，请快完成验证', 'confirm')
        # TODO 去认证 数据表 添加 字段编辑是否认证
        from app.model.user import User
        nickname = self.form.nickname.data
        account = self.form.account.data
        password = self.form.password.data
        User.register_by_email(nickname=nickname,
                               account=account,
                               password=password,
                               type=self.client_type)

    def register_by_mina(self):
        """微信小程序注册"""
        # 使用 code 请求微信 获取open id
        from app.model.user import User
        wx_code = self.form.data
        self.__get_mina_by_code(wx_code)
        User.register_by_mani(account=self.wx_data['openid'],
                              type=self.client_type)

    def get_mina_by_code(self, wx_code):
        """
        通过code向微信请求获取session_key和opendd
        :param code: 小程序的临时凭证
        :return: dict
        """
        wx_app = current_app.config['WX_APPID']
        wx_secret = current_app.config['WX_SECRET']
        wx_login_url = current_app.config['WX_LOGIN_URL']
        wx_url = wx_login_url.format(wx_app, wx_secret, wx_code)  # python字符串拼接

        res = requests.get(wx_url)
        wx_data = json.loads(res.content)
        if not wx_data:
            raise AuthFailedException(msg='获取session_id及openid异常,微信内部错误')
        else:
            if 'errcode' in wx_data:
                msg = '微信授权错误' if wx_data['errcode'] == 40163 else '微信授权失败'
                raise AuthFailedException(error_code=wx_data['errcode'], msg=msg)
            else:
                self.wx_data = res
